#include "Game.h"

IGame* createGame( HINSTANCE hInst, HWND hWnd )
{
	return new Game( hInst, hWnd );
}

Game::Game( HINSTANCE hInst, HWND hWnd ) :
	m_input( hInst, hWnd )
{
	// initialize camera
	m_camera.hand = Camera::RIGHTHANDED;

	m_camera.eye = float3( 0, 0, 20.f );
	m_camera.at  = float3( 0, 0, 0 );
	m_camera.up  = float3( 0, 1, 0 );

	m_camera.projectionType = Camera::PERSPECTIVE_FOV;
	m_camera.perspectiveFov.fovy = D3DXToRadian(45.f);
	m_camera.perspectiveFov.aspect = 1024.f/768.f;

	m_camera.zn = 1.0f;
	m_camera.zf = 100.0f;
}

Game::~Game()
{
	m_d3dDevice = 0;
}

void Game::onCreateGraphics( D3DDevice device )
{
	m_d3dDevice = device;

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 world = identity44();
	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_WORLD, &world );
	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );

	// initialize rigid circles
	RigidBody body;
	m_rc1.setup( device, body, 10, 1, float4( 1.f, 0.5f, 0.5f, 0.5f ) );
	
	body.pos = float3( 5.f, 0.f, 0.f );
	m_rc2.setup( device, body, 5, 1, float4( 1.f, 0.75f, 0.25f, 0.25f ) );

	// initialize spring constraint
	m_spring.rigidBody1 = & m_rc1.rigidBody;
	m_spring.rigidBody2 = & m_rc2.rigidBody;
	m_spring.pointOfApp2 = float3(0,1.f,0);
	m_spring.forceDensity = 0.1f;

	// initialize collision constraint
	m_collision.circleBodies.insert( &m_rc1 );
	m_collision.circleBodies.insert( &m_rc2 );

	// add rigid bodies to dynamics
	m_dynamics.dynObjects.insert( & m_rc1 );
	m_dynamics.dynObjects.insert( & m_rc2 );

	// add constraints to dynamics
	m_dynamics.constraints.insert( & m_spring );
	m_dynamics.constraints.insert( & m_collision );
}

void Game::onResetGraphics( D3DDevice device )
{
	//TODO: Add code to handle lost device ( resizing issue )

	m_d3dDevice = device;

	m_d3dDevice->SetRenderState( D3DRS_CULLMODE, D3DCULL_CW );

	float44 view = m_camera.view();
	float44 proj = m_camera.projection();

	m_d3dDevice->SetTransform( D3DTS_VIEW, &view );
	m_d3dDevice->SetTransform( D3DTS_PROJECTION, &proj );
}

void Game::onLostGraphics()
{
}

void Game::onFrameMove(float dt)
{
	m_dynamics.step(dt);
}

void Game::onFrameRender(float dt)
{
	m_dynamics.render(dt);
}

void Game::onDestroyGraphics()
{
}
